package com.tangkun.environment.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.tangkun.environment.R;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.base.CommonReturn;
import com.tangkun.environment.entity.login.VerifyReturn;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxActivityHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
import rx.functions.Action0;

/**
 * 修改手机
 */

public class XiuGaiShouJiActivity extends BaseActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.et_xiugaishouji_verify)
    EditText etXiugaishoujiVerify;
    @BindView(R.id.tv_xiugaishouji_verify)
    TextView tvXiugaishoujiVerify;
    @BindView(R.id.et_xiugaishouji_newtelephone)
    EditText etXiugaishoujiNewtelephone;
    @BindView(R.id.iv_xiugaishouji_newtelephone_delete)
    ImageView ivXiugaishoujiNewtelephoneDelete;
    @BindView(R.id.iv_newtelephone_xiugaishouji_show_or_hide)
    ImageView ivNewtelephoneXiugaishoujiShowOrHide;
    @BindView(R.id.btn_xiugaishouji_queren)
    Button btnXiugaishoujiQueren;

    private Context mContext;
    /**
     * 是否显示旧手机号
     */
    private boolean isShowOldTelephone = false;
    /**
     * 是否显示新手机号
     */
    private boolean isShowNewTelephone = false;
    /**
     * 服务器返回的验证码
     */
    private String code = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_xiugaishouji);
        ButterKnife.bind(this);
        title.setText("修改手机");
        initListener();
        //不可点击下一步，获取到验证码后才可点击
        btnXiugaishoujiQueren.setEnabled(false);
        btnXiugaishoujiQueren.setAlpha(0.5f);
        showOrHideNewTelephone();
    }

    private void initListener() {
        //监听新手机号控件删除按钮显示与隐藏
        etXiugaishoujiNewtelephone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (etXiugaishoujiNewtelephone.getText().toString().length() > 0) {
                    ivXiugaishoujiNewtelephoneDelete.setVisibility(View.VISIBLE);
                } else {
                    ivXiugaishoujiNewtelephoneDelete.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }


    /**
     * 检测手机号是否注册过了，没有注册过就发送验证码
     */
    private void checkAndSendMobileCode() {
        //手机号
        if (TextUtils.isEmpty(etXiugaishoujiNewtelephone.getText().toString())) {
            showToast("请输入手机号");
            return;
        }
        //是否是正确的手机号判断
        if (!Utils.isTruePhone(etXiugaishoujiNewtelephone.getText().toString())) {
            showToast("请输入正确的手机号");
            return;
        }
        int type = 1;//1，注册；2，找回密码
        String mobile = etXiugaishoujiNewtelephone.getText().toString().trim();//手机号
        fromNetwork.getValicode(type, mobile).compose(new RxActivityHelper<VerifyReturn>().ioMain(XiuGaiShouJiActivity.this, true))
                .subscribe(new MySubscribe<VerifyReturn>(mContext, true) {
                    @Override
                    protected void success(VerifyReturn resultBean) {
                        if (resultBean.data != null) {
                            showToast("验证码请求成功");
                            code = resultBean.data;//验证码
                            //获取到验证码后，可点击下一步
                            btnXiugaishoujiQueren.setAlpha(1);
                            btnXiugaishoujiQueren.setEnabled(true);
                            refreshSendMobileCodeBtn();
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage);
                    }
                });
    }

    /**
     * 显示与隐藏新手机号
     */
    private void showOrHideNewTelephone() {
        if (isShowNewTelephone) {//当前状态是显示密码，置为隐藏密码
            isShowNewTelephone = false;
            ivNewtelephoneXiugaishoujiShowOrHide.setImageResource(R.mipmap.ic_mima_hide);
            //隐藏旧手机号
            etXiugaishoujiNewtelephone.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {//当前状态是隐藏密码，置为显示密码
            isShowNewTelephone = true;
            ivNewtelephoneXiugaishoujiShowOrHide.setImageResource(R.mipmap.ic_mima_show);
            //显示旧手机号
            etXiugaishoujiNewtelephone.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
    }

    /**
     * 刷新获取验证码按钮
     */
    private void refreshSendMobileCodeBtn() {
        Utils.countDown(60)
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        //开始计时
                        //获取验证码不可点击
                        tvXiugaishoujiVerify.setBackgroundResource(R.drawable.shape_rectangle_green);
                        tvXiugaishoujiVerify.setEnabled(false);
                    }
                })
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        //计时完成
                        //获取验证码可点击
                        tvXiugaishoujiVerify.setBackgroundResource(R.drawable.shape_rectangle_green);
                        tvXiugaishoujiVerify.setText("获取");
                        tvXiugaishoujiVerify.setEnabled(true);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        //当前计时
                        //刷新获取验证码按钮
                        tvXiugaishoujiVerify.setText(integer + "S");
                    }
                });
    }

    @OnClick({R.id.back, R.id.tv_xiugaishouji_verify, R.id.iv_xiugaishouji_newtelephone_delete, R.id.iv_newtelephone_xiugaishouji_show_or_hide, R.id.btn_xiugaishouji_queren})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back://返回按钮
                Utils.hideSoftKeyboard(XiuGaiShouJiActivity.this, back);
                JumpHelper.finish(mContext);
                break;
            case R.id.tv_xiugaishouji_verify://获取验证码
                checkAndSendMobileCode();
                break;
            case R.id.iv_xiugaishouji_newtelephone_delete://清空新手机号
                etXiugaishoujiNewtelephone.setText("");
                break;
            case R.id.iv_newtelephone_xiugaishouji_show_or_hide://显示与隐藏新手机号
                showOrHideNewTelephone();
                break;
            case R.id.btn_xiugaishouji_queren://确认
                if (TextUtils.isEmpty(etXiugaishoujiVerify.getText().toString())) {
                    showToast("请输入验证码");
                    return;
                }
                //新手机号
                if (TextUtils.isEmpty(etXiugaishoujiNewtelephone.getText().toString())) {
                    showToast("请输入新手机号");
                    return;
                }
                //是否是正确的新手机号判断
                if (!Utils.isTruePhone(etXiugaishoujiNewtelephone.getText().toString())) {
                    showToast("请输入正确的新手机号");
                    return;
                }
                //验证码确认
                if (!code.equals(etXiugaishoujiVerify.getText().toString())) {
                    showToast("请输入正确的验证码");
                    return;
                }
                String newMobile = etXiugaishoujiNewtelephone.getText().toString();
                String valicode = etXiugaishoujiVerify.getText().toString();
                fromNetwork.changeMobile(newMobile, valicode).compose(new RxActivityHelper<CommonReturn>().ioMain(XiuGaiShouJiActivity.this, true))
                        .subscribe(new MySubscribe<CommonReturn>(mContext, true) {
                            @Override
                            protected void success(CommonReturn resultBean) {
                                showToast("修改成功");
                                //设置新手机号
                                Session.getInstance().getUserInfo().username = etXiugaishoujiNewtelephone.getText().toString();
                                Utils.hideSoftKeyboard(XiuGaiShouJiActivity.this, back);
                                JumpHelper.finish(mContext);
                            }

                            @Override
                            protected void onMyError(String errorMessage) {
                                showToast(errorMessage);
                            }
                        });
                break;
        }
    }
}
